﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.InvDoc.CheckDiffBill;
using UFIDA.U9.ISV.CheckDiffSV.Proxy;
using UFIDA.U9.ISV.CheckDiffSV;
using UFIDA.U9.SM.DealerSO;
using ufida.u9.ait.openapi.utils;
using UFIDA.U9.ER.ERBP;
using UFIDA.U9.InvDoc.Enums;

namespace ufida.u9.ait.openapi
{
    internal class CheckDiffBase
    {
        public static CheckDiffBill CreateDoc(CopyOfCheckDiffData dto)
        {
            //新增逻辑
            CheckDiffData dto1 = new CheckDiffData();
            PreDTOCopy(dto);
            DTOUtils.DTOPropCopy(dto, dto1);
            PreSave(dto1);
            CreateCheckDiffSVProxy proxy = new CreateCheckDiffSVProxy();
            proxy.CheckDiffList = new List<CheckDiffData> { dto1 };
            List<CommonArchiveDataDTOData> ret = proxy.Do();

            CheckDiffBill doc = CheckDiffBill.Finder.FindByID(ret[0].ID);

            return doc;
        }
        /// <summary>
        /// 在 传入DTO->系统标准DTO 前的处理
        /// </summary>
        /// <param name="dto">传入DTO</param>
        private static void PreDTOCopy(CopyOfCheckDiffData dto)
        {
            foreach(var linedto in dto.CheckDiffLine)
            {
                if (linedto.AccountQty != 0 || linedto.CheckQty != 0)
                {
                    //调整数量=盘点数量-账面数量
                    linedto.AdjQtySU = linedto.CheckQty - linedto.AccountQty;
                }
            }
        }

        private static void PreSave(CheckDiffData dto1)
        {

            //dto1.DescFlexField.PrivateDescSeg1; //扩展字段名称
            dto1.DocNo = "";//先自动单号,后面再更新单号
            foreach (var linedto in dto1.CheckDiffLine)
            {
                //linedto.DescFlexSegments.PrivateDescSeg1; //扩展字段名称
                //linedto.LotInfo.LotCode; //批号
                //linedto.ItemInfo.ItemGrade; //等级
                linedto.Reason = -1;
                if (linedto.AdjQtySU > 0)
                {
                    linedto.PlusQtySU=linedto.AdjQtySU;
                    linedto.AdjustType = 0; //盘盈
                }else if(linedto.AdjQtySU < 0)
                {
                    linedto.MinusQtySU = linedto.AdjQtySU * -1;
                    linedto.AdjustType = 1; //盘亏
                }
            }
        }

        public static CheckDiffBill ApproveDoc(CheckDiffBill doc)
        {
            if (doc.Status != INVDocStatus.Approving)
                throw new Exception($"单号[{doc.DocNo}]状态不为审核中");

            CheckDiffOperationSV sv = new CheckDiffOperationSV();
            sv.CheckDiffList = new List<CheckDiffBill.EntityKey>()
                        {
                            doc.Key
                        };
            sv.Status = INVDocStatus.Approved;
            List<CommonArchiveDataDTO> retdtos = sv.Do();

            return doc;
        }
    }
}
